package ru.ipo.dces.client;

import info.clearthought.layout.TableLayout;
import ru.ipo.dces.client.components.StatusBar;
import ru.ipo.dces.client.messages.PopupMessageManager;
import ru.ipo.dces.client.messages.PopupMessageType;
import ru.ipo.dces.pluginapi.Plugin;
import ru.ipo.dces.plugins.admin.LoginPluginV2;
import ru.ipo.dces.plugins.admin.ResultsPlugin;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.*;

public class ClientDialog extends JFrame {

    private JTextPane logTextPane;
    private JTabbedPane mainTabbedPane;
    private StatusBar statusBar;
    private Plugin selectedPlugin = null;
    private JPanel glassPanel;
    private PopupMessageManager messageManager;

    public JTabbedPane getMainTabbedPane() {
        return mainTabbedPane;
    }

    public StatusBar getStatusBar() {
        return statusBar;
    }

    /**
     * Удалить все Plugin'ы
     */
    public void clearLeftPanel() {
        mainTabbedPane.removeAll();
    }

    public void initGUI() {
        //set outer components and outer layout
        TableLayout outerLayout = new TableLayout(new double[][]
                {{TableLayout.FILL}, {TableLayout.FILL, TableLayout.PREFERRED}}
        );
        getContentPane().setLayout(outerLayout);
        logTextPane = new JTextPane();
        mainTabbedPane = new JTabbedPane(JTabbedPane.LEFT, JTabbedPane.SCROLL_TAB_LAYOUT);
        statusBar = new StatusBar();
//        JScrollPane logScrollPane = new JScrollPane(logTextPane);
        getContentPane().add(mainTabbedPane, "0, 0");
        getContentPane().add(statusBar, "0, 1");
//        getContentPane().add(logScrollPane, "0, 1");

        glassPanel = new JPanel();
        glassPanel.setOpaque(false);
        setGlassPane(glassPanel);

        //logTextPane adjust
        logTextPane.setEditable(false);
        logTextPane.setBackground(Color.BLACK);

        mainTabbedPane.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                int selectedIndex = mainTabbedPane.getSelectedIndex();
                Plugin newPlugin = null;
                if (selectedIndex != -1)
                    newPlugin = PluginEnvironmentImpl.getPluginByPanel(
                            (JPanel) mainTabbedPane.getComponentAt(selectedIndex)
                    );

                if (selectedPlugin != null)
                    selectedPlugin.deactivate();
                if (newPlugin != null)
                    newPlugin.activate();

                selectedPlugin = newPlugin;
            }
        });

        initialState();

        setSize(1000, 600);
        // Разместить окно по центру экрана
        setLocationRelativeTo(null);
        //setTitle("DCES Client");

        messageManager = new PopupMessageManager(getGlassPanel());
        addMouseClicksHooks();
    }

    private ArrayList<StatusBar.Message> messages = new ArrayList<StatusBar.Message>();

    private void addMouseClicksHooks() {
        long eventMask = AWTEvent.MOUSE_EVENT_MASK | AWTEvent.KEY_EVENT_MASK;
        Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
            public void eventDispatched(AWTEvent e) {
                if (e.getID() == MouseEvent.MOUSE_CLICKED || e.getID() == KeyEvent.KEY_PRESSED)
                    messageManager.removeOldestDrawnMessage();

                if (e.getID() == KeyEvent.KEY_PRESSED) {
                    KeyEvent keyEvent = (KeyEvent) e;
                    switch (keyEvent.getKeyChar()) {
                        case 'q':
                            Controller.showPopupMessage("Сообщение длинной длины, достаточно", PopupMessageType.Info);
                            break;
                        case 'w':
                            Controller.showPopupMessage("Короткое сообщение", PopupMessageType.ServerReturnedError);
                            break;
                        case 'e':
                            Controller.showPopupMessage("Длинное длинное очень длиииииииииииииииииииииииииииииииное сообщение", PopupMessageType.GeneralServerError);
                            break;
                        case 'a':
                            messages.add(Controller.getClientDialog().getStatusBar().addMessage("Какой-то процесс"));
                            break;
                        case 's':
                            if (messages.isEmpty())
                                return;

                            Controller.getClientDialog().getStatusBar().removeMessage(messages.get(0));
                            messages.remove(0);
                            break;
                    }
                }
            }
        }, eventMask);
    }

    /**
     * Начальное состояние клиента до присоединения контеста
     */
    public void initialState() {
        clearLeftPanel();

        Controller.addAdminPlugin(LoginPluginV2.class);
        Controller.addAdminPlugin(ResultsPlugin.class);
    }

    public JTextPane getLogTextPane() {
        return logTextPane;
    }

    public JPanel getGlassPanel() {
        return glassPanel;
    }

    @Override
    public void setTitle(String title) {
        super.setTitle("DCES Client");
    }

    public void showPopupMessage(String message, PopupMessageType messageType) {
        messageManager.showPopupMessage(message, messageType);
    }

}
